package cn.hd01.web.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hd01.repository.entity.MonthlyTarget;
import cn.hd01.service.MonthlyTargetService;
import cn.hd01.web.auth.Auth;
import cn.hd01.web.util.WebException;

@Controller
@RequestMapping("/monthlyTarget")
@Auth
public class MonthlyTargetController {
	
	@Autowired
	private MonthlyTargetService monthlyTargetService;
	
	@RequestMapping(method = RequestMethod.GET)
	public String index(Model m, HttpServletRequest request) {
		return "monthlyTarget";
	}

	@ResponseBody
	@RequestMapping(path = "/list", method = RequestMethod.GET)
	private Page<MonthlyTarget> find(MonthlyTarget s, @PageableDefault Pageable pageable) {
		Page<MonthlyTarget> monthlyTarget = monthlyTargetService.findAll(s, pageable);
		return monthlyTarget; 
	}

	@ResponseBody
	@RequestMapping(path = "/delete/{id}", method = RequestMethod.GET)
	private void delete(@PathVariable("id") Integer id) {
		monthlyTargetService.delete(id);
	}

	@ResponseBody
	@RequestMapping(path = "/save", method = RequestMethod.POST)
	private void save(MonthlyTarget monthlyTarget) {

		validateMonthlyTarget(monthlyTarget);
		
		if(monthlyTarget.getId() == null){//保存
			
			Date date = new Date();
			monthlyTarget.setCreateTime(date);
			monthlyTargetService.save(monthlyTarget);
			
		}else {//更新
			monthlyTargetService.updateMonthlyTarget(monthlyTarget.getAmount(), monthlyTarget.getTargetTime(), monthlyTarget.getId());
		}
	}
	
	private void validateMonthlyTarget(MonthlyTarget monthlyTarget){
		
		if(StringUtils.isEmpty(monthlyTarget.getAmount())){
			throw new WebException(HttpStatus.BAD_REQUEST, "目标金额不能为空");
		}
		if(StringUtils.isEmpty(monthlyTarget.getTargetTime())){
			throw new WebException(HttpStatus.BAD_REQUEST, "目标时间不能为空");
		}
	}
}
